<template>
	<view class="sms-code">
		<view class="sms-code-main" @click="getSmsCode">
			<slot name="button">
				<u-button shape="circle" :customStyle="submitCustomStyle">
					{{code_tips}}
				</u-button>
			</slot>
		</view>
		<u-code ref="uCode" :seconds="seconds" changeText="X秒重新获取" @change="codeChange" @end="codeEnd"></u-code>
	</view>
</template>
<script>
	export default {
		name: "send-sms-code",
		data() {
			return {
				code_tips: '获取验证码',
				// 获取验证码点击状态 true-可点击 false-不可点击
				is_sms: true,
				// 提交按钮样式
				submitCustomStyle: {
					border: '1rpx solid #d7d7d7',
					// backgroundColor: "#FF2D71",
					fontSize: "24rpx",
					fontWeight: '500'
				},
			};
		},
		// 此处定义传入的参数
		props: {
			// 请求接口地址
			url: {
				type: String,
				default: '',
			},
			// 验证码时间
			seconds: {
				type: Number,
				default: 60,
			},
			// 手机号
			mobile: {
				type: String,
				default: '',
			},
			type: {
				type: Number,
				default: 1,
			},
		},
		watch: {},
		mounted() {},
		methods: {
			// 发送验证码
			getSmsCode() {
				if (this.type == 1) {
					if (this.mobile == '') {
						this.showToast('请输入手机号');
						return false;
					}
					if (!this.$formCheck.phone(this.mobile)) {
						this.showToast('手机号格式不正确');
						return false;
					}
				}
				if (this.$refs.uCode.canGetCode) {
					if (this.is_sms == false) return
					this.is_sms = false;
					uni.showLoading({
						title: '正在获取验证码'
					})
					if (this.type == 1) {
						this.$post(this.url, {
							mobile: this.mobile
						}).then(res => {
							uni.hideLoading();
							this.showToast(res.msg)
							if (res.code == 200) {
								// 这里此提示会被this.start()方法中的提示覆盖
								this.$refs.uCode.start();
								this.$emit('complete');
							} else {
								this.is_sms = true;
							}
						}).catch(ex => {
							uni.hideLoading();
							this.is_sms = true;
							this.$errorToast();
						});
					} else {
						this.$post(this.url).then(res => {
							uni.hideLoading();
							this.showToast(res.msg)
							if (res.code == 200) {
								// 这里此提示会被this.start()方法中的提示覆盖
								this.$refs.uCode.start();
								this.$emit('complete');
							} else {
								this.is_sms = true;
							}
						}).catch(ex => {
							uni.hideLoading();
							this.is_sms = true;
							this.$errorToast();
						});
					}
				} else {
					this.$showToast('倒计时结束后再发送');
				}
			},
			// 验证码倒计时
			codeChange(e) {
				this.code_tips = e;
				this.$emit('change', e);
			},
			// 验证码倒计时结束
			codeEnd() {
				this.is_sms = true;
			},
			// 提示框
			showToast(msg) {
				this.$showToast(msg)
			},
		},
	}
</script>
<style lang="scss" scoped>
	.sms-code {
		width: 200rpx;

		.u-button {
			height: 60rpx;
		}
	}
</style>